//
//  ComposeViewController.swift
//  SinaBlog
//
//  Created by macs on 15/11/18.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

//MARK : BUG,点击图片按钮, toolbar 消失,微博发送不出去

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.randomColor()
        // Do any additional setup after loading the view.
        setupUI()
    }
    
    @objc private func pictureDidClick () {
        
        picSelecteVc.collectionView?.snp_updateConstraints(closure: { (make) -> Void in
            make.height.equalTo(240 + 160)
        })
        
    }
    
    @objc private func emojiDidClick () {
        
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emojikeyBoard : nil
        
        textView.becomeFirstResponder()
        
    }
    
    @objc private func closeDidClick () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func composeDidClick () {
        
        guard let access_token = AccessViewModel().access_token else{
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        let parameters = ["access_token" : access_token, "status" : textView.fullText()]
        print(textView.fullText())
        if picSelecteVc.iconArray.count >= 1 {
            let urlPic = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            let image = picSelecteVc.iconArray.first
            let imageData = UIImagePNGRepresentation(image!)
            Networktools.shareTools.uploadPicture(urlPic, parameters: parameters, imageData: imageData!) { (result, error) -> () in
                
                if error != nil {
                    SVProgressHUD.showErrorWithStatus(NetErrorTip)
                    print(error)
                    return
                }
                
                SVProgressHUD.showWithStatus("发布成功")
                self.dismissViewControllerAnimated(true, completion: nil)
            }
        } else {
            
            let urlString = "2/statuses/update.json"
            Networktools.shareTools.requestJsonDict(HTTPType.POST, urlSting: urlString, parameters: parameters) { (result, error) -> () in
                if(error != nil){
                    SVProgressHUD.showWithStatus(NetErrorTip)
                    print(error)
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发布成功")
                self.dismissViewControllerAnimated(true, completion: nil)
                
            }
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        textView.becomeFirstResponder()
    }
    
    func setupUI () {
        
        setupNav()
        setupTextView()
        setupPicSelecteVc()
        setupToolBar()
        //注册通知
        registerNotification()
    }
    
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        //取消监听者
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    @objc private func keyBoardChange(notify : NSNotification) {
        //        print(notify)
        
        //获取到键盘变化位置时间
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        //获取到键`盘变化后的位置
        let rect = (notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        //动画曲线值,
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! Int
        
        //设置 toolbar的约束
        let offset = -screenH + rect.origin.y
        self.toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offset)
        }
        UIView.animateWithDuration(duration) { () -> Void in
            //MARK : 处理键盘 toolbar 跳动问题
            //设置自动化曲线值,这个值为7 设置之后. duration 失效
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    lazy var textView : EmojiTextView = {
        
        let text = EmojiTextView()
        //        text.text = "分享新鲜事..."
        text.font = UIFont.systemFontOfSize(19)
        text.textColor = UIColor.darkGrayColor()
        //设置键盘消失的模式
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        //设置弹簧效果开启
        text.alwaysBounceVertical = true
        return text
    }()
    //懒加载表情键盘
    lazy var  emojikeyBoard : EmojiKeyBoardView = EmojiKeyBoardView { [weak self] (em) -> () in
        
        //
        self?.textView.insertAttrateText(em)
    }
    
    private lazy var placeHole = UILabel(title: "分享新鲜事...", size: 19, color: UIColor.lightGrayColor())
    
    private lazy var toolBar : UIToolbar = UIToolbar()
    
    //移植图片选择控制器到发布微博界面上
    private lazy var picSelecteVc  = PictureSelectorViewController()
    
}

extension ComposeViewController : UITextViewDelegate {
    
    func textViewDidChangeSelection(textView: UITextView) {
        placeHole.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
}

extension ComposeViewController {
    
    func setupPicSelecteVc() {
        
        addChildViewController(picSelecteVc)
        view.addSubview(picSelecteVc.view)
        
        picSelecteVc.collectionView?.snp_makeConstraints(closure: { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(0)
        })
        
    }
    
    func setupToolBar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        //添加子空间
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"pictureDidClick"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"emojiDidClick"],
            ["imageName": "compose_addbutton_background"]]
        for dict in itemSettings {
            let barBtn = UIBarButtonItem(imageName:dict["imageName"]!, target: self, actionName: dict["action"])
            items.append(barBtn)
            //创建弹簧,将弹簧添加
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        //一出最后一个弹簧
        items.removeLast()
        toolBar.items = items
    }
    
    func setupTextView () {
        
        view.addSubview(textView)
        //设置代理
        textView.delegate = self
        textView.snp_makeConstraints { (make) -> Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(screenH / 3)
        }
        
        //创建lable.设置为 placehole
        textView.addSubview(placeHole)
        placeHole.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
        
    }
    
    //设置导航条
    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeDidClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "composeDidClick")
        navigationItem.rightBarButtonItem?.enabled = false
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //        titleView.backgroundColor = UIColor.randomColor()
        navigationItem.titleView = titleView
        
        //添加子控件
        let lable  = UILabel(title: "发微博", size: 17, color: UIColor.darkGrayColor())
        let nameLable = UILabel(title: AccessViewModel().name ?? "", size: 14, color: UIColor.lightGrayColor())
        titleView.addSubview(lable)
        titleView.addSubview(nameLable)
        
        //设置约束
        lable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
        nameLable.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(lable.snp_bottom)
            make.centerX.equalTo(lable.snp_centerX)
        }
        
    }
    
}
